<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./OL_SDK/include-openlayers-local.js"></script>
  <script src="./libs/gaode.js"></script>
  <script src="https://lib.baomitu.com/jquery/2.2.4/jquery.js"></script>
  <style>
    #popup {
      width: 100px;
      height: 80px;
      border: 1px solid #333;
      position: absolute;
      z-index: 1000;
      top: 0;
      left: 0;
      background-color: #fff;
      display: none;
    }
  </style>
</head>

<body>
  <div id="popup">
    <button id="close">关闭</button>
    <div id="content"></div>
  </div>
  <div id="map">
  </div>
  <script>
    var map = new ol.Map({
      target: "map",
      layers: [gaode],
      view: new ol.View({
        projection: 'EPSG:4326',
        center: [114.30, 30.50],
        zoom: 4
      })
    })
    var p1 = new ol.Feature({
      geometry: new ol.geom.Point([114.30, 30.50]),
      name: "武汉"
    })
    var p2 = new ol.Feature({
      geometry: new ol.geom.Point([118, 30.50]),
      name: "苏州"
    })
    let style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 20,
        fill: new ol.style.Fill({
          color: "red"
        })
      })
    })
    const source = new ol.source.Vector({
      features: [p1, p2]
    })
    const layer = new ol.layer.Vector({
      source,
      style
    })
    map.addLayer(layer)
    /* 1、自定义popup-html-css */
    /* 2、点击要素--获取坐标 让popup在对应的坐标位置显示 */
    map.on('pointermove', function (e) {
      var pixel = map.getEventPixel(e.originalEvent);
      var hit = map.hasFeatureAtPixel(pixel);
      map.getTargetElement().style.cursor = hit ? 'pointer' : '';
    });
    map.on('click', function (evt) {
      //判断当前单击处是否有要素，捕获到要素时弹出popup
      var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) { return feature; });
      if (feature) {
        var position = feature.getGeometry().getCoordinates();
        /* 必须放在feature */
        var pixel = map.getPixelFromCoordinate(position)
        var name = feature.get("name")
        $("#popup").show(500).css({
          left: pixel[0] + "px",
          top: pixel[1] + "px"
        })
        $("#content").html(name)
      }
    });
    $("#close").click(function () {
      $("#popup").hide(500)
    })
  </script>
</body>

</html>